# filepath: d:\CompanyProject\Gitee\DBCompareX\backend\app\models\task_data_sync\execution_log.py
"""
执行日志模块，负责管理任务执行日志的查询和管理
"""
from typing import List, Dict, Any, Optional, Tuple
from datetime import datetime
from bson import ObjectId
import logging

from ...database.mongodb import (
    task_data_sync_execution_log_collection,
    task_data_sync_setting_collection
)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ExecutionLogManager:
    """执行日志管理器，处理执行日志的查询和管理"""
    
    execution_log_collection = task_data_sync_execution_log_collection
    setting_collection = task_data_sync_setting_collection
    
    @classmethod
    async def get_execution_logs_by_task(cls, task_id: str, limit: int = 10) -> List[Dict[str, Any]]:
        """
        获取任务的执行日志列表
        
        Args:
            task_id: 数据同步任务配置ID
            limit: 最大返回数量
            
        Returns:
            执行日志列表
        """
        cursor = cls.execution_log_collection.find(
            {"task_data_sync_setting_id": task_id}
        ).sort("created_at", -1).limit(limit)
        
        results = await cursor.to_list(length=limit)
        
        # 转换ObjectId为字符串
        for result in results:
            result["_id"] = str(result["_id"])
            
        return results
    
    @classmethod
    async def query_execution_logs(
        cls, 
        task_id: Optional[str] = None, 
        batch_no: Optional[str] = None, 
        status: Optional[int] = None,
        page: int = 1,
        page_size: int = 10
    ) -> Tuple[List[Dict[str, Any]], int]:
        """
        查询执行日志记录
        
        Args:
            task_id: 任务ID (可选)
            batch_no: 批次号 (可选)
            status: 状态 (可选)
            page: 当前页码，从1开始
            page_size: 每页记录数
            
        Returns:
            执行日志列表和总记录数
        """
        # 构建查询条件
        query = {}
        if task_id:
            query["task_data_sync_setting_id"] = task_id
        if batch_no:
            query["batch_no"] = batch_no
        if status is not None:
            query["status"] = status
        
        # 计算总记录数
        total = await cls.execution_log_collection.count_documents(query)
        
        # 计算跳过的记录数
        skip = (page - 1) * page_size
        
        # 查询记录
        cursor = cls.execution_log_collection.find(query).sort("created_at", -1).skip(skip).limit(page_size)
        results = await cursor.to_list(length=page_size)
        
        # 转换ObjectId为字符串并获取任务名称
        tasks_map = {}
        task_ids = []
        
        for result in results:
            result["_id"] = str(result["_id"])
            task_id = result["task_data_sync_setting_id"]
            if task_id not in task_ids:
                task_ids.append(task_id)
        
        # 批量查询任务信息
        if task_ids:
            task_cursor = cls.setting_collection.find({"_id": {"$in": [ObjectId(tid) for tid in task_ids]}})
            task_results = await task_cursor.to_list(length=None)
            
            for task in task_results:
                tasks_map[str(task["_id"])] = task.get("task_name", "未命名任务")
            
        # 将任务名称添加到结果中
        for result in results:
            result["task_name"] = tasks_map.get(result["task_data_sync_setting_id"], "未命名任务")
            
        return results, total
    
    @classmethod
    async def get_execution_log(cls, execution_log_id: str) -> Dict[str, Any]:
        """
        获取执行日志
        
        Args:
            execution_log_id: 执行日志ID
            
        Returns:
            执行日志信息
        """
        result = await cls.execution_log_collection.find_one({"_id": ObjectId(execution_log_id)})
        if result:
            result["_id"] = str(result["_id"])
            
            # 获取任务名称
            task_id = result["task_data_sync_setting_id"]
            task_info = await cls.setting_collection.find_one({"_id": ObjectId(task_id)})
            if task_info:
                result["task_name"] = task_info.get("task_name", "未命名任务")
            else:
                result["task_name"] = "未命名任务"
                
        return result
    
    @classmethod
    async def update_execution_log(cls, execution_log_id: str, status: int, message: str) -> None:
        """
        更新执行日志状态
        
        Args:
            execution_log_id: 执行日志ID
            status: 状态
            message: 消息
        """
        await cls.execution_log_collection.update_one(
            {"_id": ObjectId(execution_log_id)},
            {"$set": {"status": status, "message": message}}
        )
    
    @classmethod
    async def get_task_names(cls) -> List[Dict[str, Any]]:
        """
        获取所有任务名称列表，用于下拉选择
        
        Returns:
            任务名称列表
        """
        # 查询所有配置
        cursor = cls.setting_collection.find({}, {"task_name": 1})
        results = await cursor.to_list(length=None)
        
        # 格式化结果
        task_names = []
        for result in results:
            task_names.append({
                "id": str(result["_id"]),
                "name": result.get("task_name", "未命名任务")
            })
            
        return task_names